﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using TamoCRM.Core;
using TamoCRM.Core.Commons.Utilities;
using TamoCRM.Domain.Contacts;
using TamoCRM.Domain.HandoverToDistributorDetails;
using TamoCRM.Domain.HandoverToDistributors;
using TamoCRM.Domain.Levels;
using TamoCRM.Domain.Phones;
using TamoCRM.Services.Channels;
using TamoCRM.Services.Collectors;
using TamoCRM.Services.Contacts;
using TamoCRM.Services.HandoverToDistributorDetails;
using TamoCRM.Services.HandoverToDistributors;
using TamoCRM.Services.ImportExcels;
using TamoCRM.Services.Levels;
using TamoCRM.Services.Phones;
using TamoCRM.Services.Schools;
using TamoCRM.Services.UserRole;
using TamoCRM.Web.Framework;
using TamoCRM.Web.Framework.ActionFilters;
using TamoCRM.Web.Framework.Controllers;
using TamoCRM.Web.Mvc.Areas.Admin.Models.Contacts;

namespace TamoCRM.Web.Mvc.Areas.Admin.Controllers
{
    public class ImportController : AdminController
    {


        [HttpGet]
        public ActionResult GoFilter()
        {
            ViewBag.SourceTypes = StoreData.ListSourceType.Where(c => c.SourceTypeId == (int)SourceType.MO || c.SourceTypeId == (int)SourceType.CC).ToList();
            var model = new GoFilterModel { AllSourceTypes = ViewBag.SourceTypes };
            return View(model);
        }

        [HttpPost]
        public ActionResult GoFilter(GoFilterModel model, FormCollection forms)
        {
            var handover = new HandoverToDistributorInfo
                               {
                                   Total = model.Total,
                                   BranchId = model.BranchId,
                                   UserId = UserRepository.GetCurrentUserInfo().UserID,
                                   ToDate = string.IsNullOrEmpty(model.ToDate)
                                                ? DateTime.Now.Date.AddDays(1).AddSeconds(-1)
                                                : DateTime.ParseExact(model.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).AddDays(1).AddSeconds(-1),
                                   FromDate = string.IsNullOrEmpty(model.FromDate)
                                                  ? DateTime.Now.Date
                                                  : DateTime.ParseExact(model.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture),
                               };
            handover.HandoverId = HandoverToDistributorRepository.Create(handover);

            //source types
            if (model.PostedSourceTypes != null)
            {
                foreach (var sourceTypeId in model.PostedSourceTypes.SourceTypeIds)
                {
                    //channels
                    foreach (var channelInfo in StoreData.ListChannel)
                    {
                        if (string.IsNullOrEmpty(forms.Get(channelInfo.ChannelId + "_chkChannel"))) continue;
                        var channelId = channelInfo.ChannelId;

                        //schools
                        foreach (var schoolInfo in StoreData.ListSchool)
                        {
                            if (string.IsNullOrEmpty(forms.Get(schoolInfo.SchoolId + "_chkSchool"))) continue;
                            var schoolId = schoolInfo.SchoolId;

                            var detail = new HandoverToDistributorDetailInfo
                                             {
                                                 HandoverId = handover.HandoverId,
                                                 SourceTypeId = sourceTypeId,
                                                 ChannelId = channelId,
                                                 SchoolId = schoolId
                                             };
                            HandoverToDistributorDetailRepository.Create(detail);
                        }
                    }
                }
                HandoverToDistributorRepository.Update(handover);
            }

            return View(model);
        }

        [HttpGet]
        public ActionResult GoFilterCCL0()
        {
            //ViewBag.SourceTypes = SourceTypeRepository.GetAll();
            //ViewBag.Channels = ChannelRepository.GetAll();
            var schools = SchoolRepository.GetAll();
            schools.Insert(0, new Domain.Schools.SchoolInfo { SchoolId = 0, Name = "Tất cả" });
            ViewBag.Schools = schools;
            //ViewBag.Branches = BranchRepository.GetAll();
            //var model = new GoFilterModel();
            //model.AllSourceTypes = ViewBag.SourceTypes;
            var channels = ChannelRepository.GetAll();
            channels.Insert(0, new Domain.Channels.ChannelInfo { ChannelId = 0, Name = "Tất cả" });
            ViewBag.Channels = channels;
            return View();
        }

        [HttpGet]
        public ActionResult GoFilterMOL0()
        {
            //ViewBag.SourceTypes = SourceTypeRepository.GetAll();
            //ViewBag.Channels = ChannelRepository.GetAll();
            var schools = SchoolRepository.GetAll();
            schools.Insert(0, new Domain.Schools.SchoolInfo { SchoolId = 0, Name = "Tất cả" });
            ViewBag.Schools = schools;
            //ViewBag.Branches = BranchRepository.GetAll();
            //var model = new GoFilterModel();
            //model.AllSourceTypes = ViewBag.SourceTypes;
            var channels = ChannelRepository.GetAll();
            channels.Insert(0, new Domain.Channels.ChannelInfo { ChannelId = 0, Name = "Tất cả" });
            ViewBag.Channels = channels;
            return View();
        }

        public ActionResult CCL2()
        {
            var collectors = CollectorRepository.GetAll();
            collectors.Insert(0, new Domain.Collectors.CollectorInfo { CollectorId = 0, Name = "Tất cả" });
            ViewBag.Collectors = collectors;
            var channels = ChannelRepository.GetAll();
            channels.Insert(0, new Domain.Channels.ChannelInfo { ChannelId = 0, Name = "Tất cả" });
            ViewBag.Channels = channels;
            var imports = ImportExcelRepository.GetAll();
            foreach (Domain.ImportExcels.ImportExcelInfo info in imports)
            {
                if (!string.IsNullOrEmpty(info.FilePath))
                {
                    int index = info.FilePath.LastIndexOf("\\");
                    if (index > -1) info.FilePath = info.FilePath.Substring(index);
                }
            }
            imports.Insert(0, new Domain.ImportExcels.ImportExcelInfo { ImportId = 0, FilePath = "Tất cả" });
            ViewBag.ImportExcels = imports;
            return View();
        }

        //Lay danh sach CC
        public ActionResult CCL0()
        {
            var collectors = CollectorRepository.GetAll();
            collectors.Insert(0, new Domain.Collectors.CollectorInfo { CollectorId = 0, Name = "Tất cả" });
            ViewBag.Collectors1 = collectors;
            var channels = ChannelRepository.GetAll();
            channels.Insert(0, new Domain.Channels.ChannelInfo { ChannelId = 0, Name = "Tất cả" });
            ViewBag.Channels1 = channels;
            var levels = LevelRepository.GetAll();
            levels.Insert(0, new LevelInfo
                           {
                               LevelId = 0,
                               Name = "Tất cả",
                           });
            ViewBag.Levels1 = levels.Where(x => x.LevelId < 3).ToList();
            var imports = ImportExcelRepository.GetAllByTypeId((int)SourceType.CC);
            foreach (Domain.ImportExcels.ImportExcelInfo info in imports)
            {
                if (string.IsNullOrEmpty(info.FilePath)) continue;

                var index = info.FilePath.LastIndexOf("\\");
                if (index > -1) info.FilePath = info.FilePath.Substring(index);
            }
            imports.Insert(0, new Domain.ImportExcels.ImportExcelInfo { ImportId = 0, FilePath = "Tất cả" });
            ViewBag.ImportExcels1 = imports;
            return View();
        }

        //Lay danh sach MO
        public ActionResult MOL0()
        {
            var collectors = CollectorRepository.GetAll();
            collectors.Insert(0, new Domain.Collectors.CollectorInfo { CollectorId = 0, Name = "Tất cả" });
            ViewBag.Collectors1 = collectors;
            var channels = ChannelRepository.GetAll();
            channels.Insert(0, new Domain.Channels.ChannelInfo { ChannelId = 0, Name = "Tất cả" });
            ViewBag.Channels1 = channels;

            var levels = LevelRepository.GetAll();
            levels.Insert(0, new LevelInfo
                           {
                               LevelId = 0,
                               Name = "Tất cả",
                           });
            ViewBag.Levels1 = levels.Where(x => x.LevelId < 3).ToList();


            var imports = ImportExcelRepository.GetAllByTypeId((int)SourceType.MO);
            foreach (var info in imports)
            {
                if (string.IsNullOrEmpty(info.FilePath)) continue;
                var index = info.FilePath.LastIndexOf("\\");
                if (index > -1) info.FilePath = info.FilePath.Substring(index);
            }
            imports.Insert(0, new Domain.ImportExcels.ImportExcelInfo { ImportId = 0, FilePath = "Tất cả" });
            ViewBag.ImportExcels1 = imports;
            return View();
        }

        public ActionResult ImportErrors()
        {
            var collectors = CollectorRepository.GetAll();
            collectors.Insert(0, new Domain.Collectors.CollectorInfo { CollectorId = 0, Name = "Tất cả" });
            ViewBag.Collectors1 = collectors;
            var channels = ChannelRepository.GetAll();
            channels.Insert(0, new Domain.Channels.ChannelInfo { ChannelId = 0, Name = "Tất cả" });
            ViewBag.Channels1 = channels;
            var imports = ImportExcelRepository.GetAll();
            foreach (var info in imports)
            {
                if (string.IsNullOrEmpty(info.FilePath)) continue;
                var index = info.FilePath.LastIndexOf("\\");
                if (index > -1) info.FilePath = info.FilePath.Substring(index);
            }
            imports.Insert(0, new Domain.ImportExcels.ImportExcelInfo { ImportId = 0, FilePath = "Tất cả" });
            ViewBag.ImportExcels1 = imports;
            return View();
        }

        public ActionResult DuplicateMo()
        {
            var collectors = CollectorRepository.GetAll();
            collectors.Insert(0, new Domain.Collectors.CollectorInfo { CollectorId = 0, Name = "Tất cả" });
            ViewBag.Collectors1 = collectors;
            var channels = ChannelRepository.GetAll();
            channels.Insert(0, new Domain.Channels.ChannelInfo { ChannelId = 0, Name = "Tất cả" });
            ViewBag.Channels1 = channels;
            var imports = ImportExcelRepository.GetAll();
            foreach (var info in imports)
            {
                if (string.IsNullOrEmpty(info.FilePath)) continue;
                var index = info.FilePath.LastIndexOf("\\");
                if (index > -1) info.FilePath = info.FilePath.Substring(index);
            }
            imports.Insert(0, new Domain.ImportExcels.ImportExcelInfo { ImportId = 0, FilePath = "Tất cả" });
            ViewBag.ImportExcels1 = imports;
            return View();
        }

        [NotAuthorizeAttribute]
        public JsonResult GetForImportTeam(int branchId, int collectorId, int channelId, int importId, int levelId, int sourceTypeId, int schoolId, int statusId, int page, int rows)
        {
            var list = new MyContactListModel();
            var lstModel = new List<ContactModel>();
            int totalRecords;
            var data = ContactRepository.GetForImportTeam(branchId, collectorId, channelId, importId, levelId, sourceTypeId, schoolId, statusId, page, rows, out totalRecords);
            foreach (var info in data)
            {
                var objModel = ObjectHelper.Transform<ContactModel, ContactInfo>(info);
                var collector = CollectorRepository.GetInfo(info.CollectorId);
                var channel = ChannelRepository.GetInfo(info.ChannelId);
                var phones = PhoneRepository.GetByContact(info.Id);
                foreach (var phone in phones)
                {
                    if (phone.IsPrimary == 1)
                    {
                        objModel.Mobile = phone.PhoneNumber;
                    }
                    else if (phone.PhoneType == PhoneType.HomePhone.ToString())
                    {
                        objModel.Tel = phone.PhoneNumber;
                    }
                    else
                    {
                        objModel.Mobile2 = phone.PhoneNumber;
                    }

                }
                if (collector != null) objModel.CollectorName = collector.Name;
                if (channel != null) objModel.ChannelName = channel.Name;
                lstModel.Add(objModel);
            }
            list.UserData = totalRecords;
            list.Rows = lstModel;
            list.Page = page;
            list.Total = (totalRecords / rows) + 1;
            list.Records = rows;
            return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }
}
